<template>
  <view class="container">
    <sar-form
      :model="form"
      ref="ruleFormRef"
      direction="horizontal"
      label-align="start"
      label-valign="center"
      star-position="right"
      :rules="rules"
      card
    >
      <sar-form-item label="名称" required name="mealName">
        <sar-input v-model="form.mealName" placeholder="请输入食物名称" clearable />
      </sar-form-item>
      <sar-form-item label="类别" required name="mealKind">
        <sar-picker-input
          v-model="form.mealKind"
          placeholder="请选择食物类别"
          title="食物类别"
          :columns="mealKinds"
        />
      </sar-form-item>
      <sar-form-item label="来源(店铺)" required name="mealSource">
        <sar-input v-model="form.mealSource" placeholder="请输入食物来源" clearable />
      </sar-form-item>
      <sar-form-item label="价格" required name="mealPrice">
        <sar-input v-model="form.mealPrice" placeholder="请输入食物价格" clearable />
      </sar-form-item>
      <sar-form-item label="图片" required name="fileList"
        ><sar-upload v-model="form.fileList" :after-read="afterRead" :max-count="1">
          <template #select>
            <view style="display: flex; flex-direction: column; align-items: center">
              <sar-icon size="60rpx" family="demo-icons" name="xiangji" />
              <view style="font-size: 24rpx; margin-top: 8rpx">上传图片</view>
            </view>
          </template>
        </sar-upload>
      </sar-form-item>
      <sar-form-item label="备注">
        <sar-input v-model="form.mealRemark" type="textarea" show-count clearable />
      </sar-form-item>
      <sar-form-item>
        <sar-button @click="submitMealInfo(ruleFormRef)">添加</sar-button>
      </sar-form-item>
    </sar-form>
  </view>
</template>

<script setup lang="ts">
  import { ref, reactive } from 'vue';
  import { onLoad } from '@dcloudio/uni-app';
  import { getMealKindsAPI } from '@/services/mealkind';
  import type { MealKindType } from '@/types/mealkind';
  import type { UploadFileItem } from 'sard-uniapp';
  import { uploadFile } from '@/services/upload';
  import { insertMealAPI } from '@/services/meal';
  import { rules } from './vaild/vaildRules';
  import { type FormExpose, type FieldValidateError } from 'sard-uniapp';

  const mealKinds = ref<Array<MealKindType[]>>([[]]);
  const ruleFormRef = ref<FormExpose>();

  const form = reactive({
    mealName: '',
    mealSource: '',
    mealPrice: '',
    mealRemark: '',
    fileList: [] as any[],
    mealKind: '',
  });

  const getMealKindsData = async () => {
    const res = await getMealKindsAPI();
    mealKinds.value = [
      res.data.map((item) => {
        return { ...item, label: item.kindName, value: item.id };
      }),
    ];
  };

  onLoad(() => {
    getMealKindsData();
  });

  // 新增图片
  const afterRead = async (fileItem: UploadFileItem) => {
    form.fileList = [];
    // 当设置 mutiple 为 true 时, file 为数组格式，否则为对象格式
    uni.navigateTo({
      url: `/pages/cropper/cropper?destWidth=200&rectWidth=200&src=${fileItem.file?.path}`,
      events: {
        cropperPicPath: (path: string) => {
          form.fileList.push({
            url: path,
          });
        },
      },
    });
  };

  const submitMealInfo = (formEl?: FormExpose) => {
    if (!formEl) {
      return;
    }
    formEl
      .validate()
      .then(async () => {
        const res = await uploadFile(form.fileList);
        if (res && res.data) {
          const InsertRes = await insertMealAPI({
            ...form,
            //@ts-ignore
            mealKind: parseInt(form.mealKind[0]),
            mealImage: res.data,
          });
          if (InsertRes.code === 200) {
            formEl.reset();
          }
        }
      })
      .catch((error: FieldValidateError[]) => {
        console.log('error submit!', error);
      });
  };
</script>

<style lang="scss"></style>
